import {createRouter,createWebHashHistory, RouteRecordRaw} from 'vue-router'
// import {useStore} from "vuex" //会返回undefined
import store from "@/store/index.js"

const routes = [
    {
        name:'home',
        path:'/',
        meta:{
            title:'首页'
        },
        component:() =>  import("@/components/Home.vue"),
        redirect:'/welcome',
        children:[
            {
                name:'welcome',
                path:'/welcome',
                meta:{
                    title:'欢迎页'
                },
                component:() => import("@/views/welcome.vue")
            }
        ]
    },
    {
        name:"404",
        path:'/404',
        meta:{
            title:'页面不存在'
        },
        component:() => import("@/views/404.vue")
    },
    {
        name:'login',
        path:'/login',
        meta:{
            title:'登录'
        },
        component:() => import("@/views/login.vue")
    }
]
const router = createRouter({
    history:createWebHashHistory(),
    routes:routes as unknown as RouteRecordRaw[]
})
console.log(store)

router.beforeEach(async (to, from, next) => {
    console.log('to.name',to.name)
    if (to.name) {
        if (router.hasRoute(to.name)) {
            console.log(222)
            document.title = to.meta.title as string;
            next()
        } else {
            console.log(333)
            next('/404')
        }
    } else {
        await store.dispatch("loadAsyncRoutes")
        let curRoute = router.getRoutes().filter(item => item.path == to.path)
        if (curRoute?.length) {
            document.title = curRoute[0].meta.title as string;
            next({ ...to, replace: true })
        } else {
            next('/404')
        }
    }
})

export default router


